import {Injectable} from '@angular/core';

import {Observable} from 'rxjs/Observable';
import {UserService} from "./user.service";
import {User} from "../entity/user";
import {Response} from "@angular/http";
import {ToastOptions, ToastData, ToastyService} from "ng2-toasty";
import {Router, ActivatedRoute} from "@angular/router";

@Injectable()
export class AuthService {

  constructor(private userService: UserService, private toastyService:ToastyService, public router: Router) {}

  isLoggedIn: boolean = false;
  compactJws:string;
  // store the URL so we can redirect after logging in
  redirectUrl: string;

  currentUser(): Observable<User> {
    return this.userService.currentUser(this.getCompactJws());
  }

  register(user: User): void {
    return this.userService.register(user);
  }

  sendRetrievePasswordMail(phone:string):Observable<boolean> {
    return this.userService.sendRetrievePasswordMail(phone);
  }

  retrievePassword(token:string, password:string):Observable<number> {
    return this.userService.retrievePassword(token, password);
  }

  getCompactJws() :string{
    if (localStorage.getItem('remember')){
      sessionStorage.setItem('compactJws', localStorage.getItem('remember'));
    }
    if (this.compactJws || sessionStorage.getItem('compactJws') ){
      return this.compactJws = sessionStorage.getItem('compactJws');
    } else {
      const toastOptions:ToastOptions = {
        title: "提示信息",
        msg: "请登录！",
        showClose: true,
        timeout: 1200,
        theme: 'bootstrap',
        onAdd: (toast:ToastData) => {},
        onRemove: (toast:ToastData) => {}
      };
      this.toastyService.success(toastOptions);
      this.isLoggedIn = false;
      this.router.navigate(['/login']);
    }
  }

  setCompactJws(compactJws:string){
    this.compactJws = compactJws;
    this.isLoggedIn = true;
  }

  login(phone:string, passWord:string): Observable<any> {
    // return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true);
    return this.userService.login(phone, passWord).do(val => {
      this.isLoggedIn = true;
      this.compactJws = val._body;
      sessionStorage.setItem('compactJws', val._body);
    });
  }

  logout(): void {
    this.isLoggedIn = false;
    sessionStorage.clear();
    localStorage.clear();
  }
}
